/**
 * <p>Title: CategoryDao.java</p>
 * <p>Description: DoNotes</p>
 * @author WangJun
 * @date 2009/11/25 14:04:46
 * @version 1.0
 */
package net.donotes.blog.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.donotes.blog.pojo.Category;
import net.donotes.util.dao.PMF;

/**
 * @author WangJun
 *
 */
public class CategoryDao {

	/**
	 * Title: addCategory
	 * @param category
	 */
	public void addCategory(Category category) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(category);
        } finally {
          //  pm.close();
        }
	}
	
	/**
	 * Title: delCategory
	 * @param category
	 */
	public void delCategory(String categoryName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Category.class);
	    query.setFilter("name == nameParam");
		query.declareParameters("String nameParam");

		List<Category> resultes = (List<Category>)query.execute(categoryName);
		if (resultes.iterator().hasNext()) {
			pm.deletePersistent(resultes.get(0));
		}
	}
	
	/**
	 * Title: getCategory
	 * @param category
	 * @return
	 */
	public Category getCategory(String categoryName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Category.class);
	    query.setFilter("name == nameParam");
		query.declareParameters("String nameParam");

		List<Category> resultes = (List<Category>)query.execute(categoryName);
		if (resultes.iterator().hasNext()) {
			return resultes.get(0);
		} else {
			return null;
		}
	}
	
	/**
	 * Title: listCategory
	 * @return
	 */
	public List<Category> listCategory() {
		List<Category> categorys = new ArrayList<Category>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Category.class);
	    try {
	    	categorys = (List<Category>) query.execute(); 	
	    } finally {
	        query.closeAll();
	        //pm.close();
	    }
	    
		return categorys;
	}
	
	/**
	 * Title: updCategory
	 * @param category
	 */
	public void updCategory(Category category) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    try {
	    	Category t = pm.getObjectById(Category.class, category.getName());
	        t.setCounter(category.getCounter());
	    } finally {
	        pm.close();
	    }
	}	
}
